package cn.lingyangwl.agile.gateway.listener;

import cn.lingyangwl.agile.gateway.model.ram.*;
import cn.lingyangwl.agile.gateway.service.*;
import cn.lingyangwl.framework.tool.core.exception.*;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author shenguangyang
 */
@Slf4j
@Component
@RabbitListener(bindings = {
        @QueueBinding(
                // 切记: 此处无需设置队列名称，否在得话，多个消费者只有一个消费者能消费数据。其它消费者无法消费数据
                value = @Queue(durable = "true"), key = ResourceSyncMQ.KEY_NOTICE_REFRESH,
                exchange = @Exchange(value = ResourceSyncMQ.EXCHANGE_REFRESH, type = ExchangeTypes.FANOUT))
})
public class ResourceSyncRefreshListener {
    @Resource
    private AuthService authService;

    @RabbitHandler
    public void onMessage(String data, Channel channel, Message message) throws Exception {
        try {
            ResourceSyncMQ mq = ResourceSyncMQ.parse(data, ResourceSyncMQ.class);
            log.info("刷新资源模块数据, size: {}", mq.getRamModuleList().size());
            authService.updateResourceModule(mq.getRamModuleList());
        } catch (Exception e) {
            log.error("消费失败: {}, msg: {}", e.getMessage(), data);
            if (e instanceof NullPointerException) {
                e.printStackTrace();
            } else if (e instanceof BizException) {
                throw e;
            }
            throw new BizException(-1, "mq消费错误");
        }
    }
}
